<template>
  <div>
    <van-nav-bar :title="register?'面经注册':'面经登录'" />
    <van-form @submit="onSubmit" ref="loginform">
      <van-field
        v-model="form.username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' },{pattern:/^[0-9a-zA-Z-_]{5,}$/,message: '用户名只少包含5个字符'}]"
      />
      <van-field
        v-model="form.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' },{pattern:/^[0-9a-zA-Z-_]{6}$/,message: '请填6位数的密码'}]"
      />
      <div style="margin: 16px; text-align:right">
        <van-button
          block
          :type="register?'primary':'warning'"
          native-type="submit"
        >{{register?'注册':'登录'}}</van-button>
        <p @click="gologin">{{register?'有账号,去登陆':'注册账号'}}</p>
      </div>
    </van-form>
  </div>
</template>

<script>
import { registerApi, loginApi } from '@/api/user'
import { mapState } from 'vuex'
export default {
  name: 'LoginView',
  props: {},
  components: {},
  data () {
    return {
      form: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    // 是否登录成功的功能
    async  onSubmit () {
      if (this.register) {
        // 注册用户
        await registerApi(this.form)
        this.$toast.success('注册成功')
      } else {
        // 用户登录
        const { data } = await loginApi(this.form)
        this.$store.commit('setTokenFn', data.token)
        // 页面路径的跳转
        this.$router.replace(this.$route.query.redirect || '/layout')
        this.$toast.success('登录成功')
      }
    },
    gologin () {
      this.$store.commit('registerFn')
      this.form = {
        username: '',
        password: ''
      }
      this.$refs.loginform.resetValidation()
    }
  },
  computed: {
    ...mapState(['register'])
  },
  watch: {},
  created () {},
  mounted () {}
}
</script>

<style lang="less" scoped>
</style>
